//
//  ExhibitDetailsViewController.m
//  ArtDog
//
//  Created by dllo on 16/9/18.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "ExhibitDetailsViewController.h"
#import "BaseCollectionView.h"
#import "HLMacro.h"
#import "ZWYNetTool.h"
#import "Masonry.h"
#import "UIImageView+WebCache.h"
#import "TopCollectionLayout.h"
#import "UIColor+Common.h"
#import "ExhibitDetailModel.h"
#import "ImageViewCollectionCell.h"
#import "ExhibitWorksModel.h"
#import "ExhibitWorkDetailsViewController.h"
#import "NSString+Common.h"
#import <WebKit/WebKit.h>

@interface ExhibitDetailsViewController ()<TopCollectionLayoutDelegate, UICollectionViewDelegate, UICollectionViewDataSource, WKNavigationDelegate, UIScrollViewDelegate>

@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) BaseCollectionView *collectionView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UIImageView *picImageView;
@property (nonatomic, strong) UIImageView *addImageView;
@property (nonatomic, strong) UILabel *galleryLabel;
@property (nonatomic, strong) UIView *baseView;

@property (nonatomic, strong) NSMutableArray<ExhibitWorksModel *> *worksArray;
@property (nonatomic, strong) ExhibitDetailModel *mainModel;

@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger count;

@end

@implementation ExhibitDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createViews];
    self.isHaveActivity = YES;
    _count = 0;
    _worksArray = [NSMutableArray array];
}

- (void)setUrlString:(NSString *)urlString
{
    _urlString = urlString;
    [self handleData];
}

- (void)handleData
{
    [ZWYNetTool GET:_urlString andBody:nil andHeader:HOSTHEADER andResponse:ZWYJSON andSuccessBlock:^(id result) {
        _mainModel = [ExhibitDetailModel modelWithDic:result[@"data"]];
        _worksArray = _mainModel.works.mutableCopy;
        [self addDataForViews];
        [_collectionView reloadData];
    } andFailureBlock:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}

- (void)addDataForViews
{
    [_picImageView sd_setImageWithURL:[NSURL URLWithString:_mainModel.exhibitPic] placeholderImage:[UIImage imageNamed:@"placeholder"]];
    _titleLabel.text = _mainModel.name;
    _nameLabel.text = [NSString stringWithFormat:@"艺术家： %@", _mainModel.artist];
    _galleryLabel.text = _mainModel.galleryName;
    
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_mainModel.exhibitDesc]]];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 / 30.0 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
}

- (void)timerAction:(NSTimer *)timer
{
    _count += 1;
    _collectionView.contentOffset = CGPointMake(_count, 0);
    if (_collectionView.contentSize.width > 0 && _collectionView.contentOffset.x >= _collectionView.contentSize.width - SCREEN_WIDTH) {
        [timer setFireDate:[NSDate distantFuture]];
    }
}

- (void)dealloc
{
    [_timer finalize];
    _timer = nil;
}

- (void)createViews
{
    _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
    [self.view addSubview:_webView];
    _webView.scrollView.contentInset = UIEdgeInsetsMake(SCREEN_WIDTH * 2 / 3 + 110, 0, 0, 0);
    _webView.scrollView.backgroundColor = [UIColor whiteColor];
    _webView.scrollView.contentOffset = CGPointMake(0, -SCREEN_WIDTH * 2 / 3 - 110);
    _webView.navigationDelegate = self;
    _webView.scrollView.delegate = self;
    
    TopCollectionLayout *layout = [[TopCollectionLayout alloc]init];
    _collectionView = [[BaseCollectionView alloc]initWithFrame:CGRectMake(0, -110 - SCREEN_WIDTH * 2 / 3, SCREEN_WIDTH, SCREEN_WIDTH * 2 / 3) collectionViewLayout:layout];
    [_webView.scrollView addSubview:_collectionView];
    
    layout.sectionInset = UIEdgeInsetsMake(15, 15, 15, 15);
    layout.minimumIteritemSpacing = 10;
    layout.delegate = self;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.showsHorizontalScrollIndicator = NO;
    
    [_collectionView registerNib:[UINib nibWithNibName:@"ImageViewCollectionCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"imageViewCollectionCell"];
    
    _titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, -105, SCREEN_WIDTH - 30, 20)];
    [_webView.scrollView addSubview:_titleLabel];
    _titleLabel.font = [UIFont boldSystemFontOfSize:16];
    
    _nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, -78, SCREEN_WIDTH - 30, 20)];
    [_webView.scrollView addSubview:_nameLabel];
    _nameLabel.font = [UIFont systemFontOfSize:13];
    _nameLabel.textColor = [UIColor colorFromHexRGB:@"8a8a8a"];
    
    for (int i = 0; i < (int)(SCREEN_WIDTH - 30) / 5; i++) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(15 + 5 * i, -45, 3, 1)];
        [_webView.scrollView addSubview:view];
        view.backgroundColor = [UIColor colorFromHexRGB:@"dddddd"];
    }
    _baseView = [[UIView alloc]initWithFrame:CGRectMake(15, -44, SCREEN_WIDTH - 30, 43)];
    [_webView.scrollView addSubview:_baseView];
    
    _picImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 5, 33, 33)];
    [_baseView addSubview:_picImageView];
    _picImageView.userInteractionEnabled = YES;
    _picImageView.contentMode = UIViewContentModeScaleAspectFill;
    _picImageView.clipsToBounds = YES;
    _picImageView.layer.cornerRadius = 33 / 2.0;
    
    _galleryLabel = [[UILabel alloc]initWithFrame:CGRectMake(43, 10, SCREEN_WIDTH - 100, 23)];
    [_baseView addSubview:_galleryLabel];
    _galleryLabel.font = [UIFont systemFontOfSize:13];
    _galleryLabel.textColor = [UIColor colorFromHexRGB:@"222222"];
    
    _addImageView = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 50, 11, 20, 20)];
    [_baseView addSubview:_addImageView];
    _addImageView.image = [UIImage imageNamed:@"add"];
    _addImageView.userInteractionEnabled = YES;
    _addImageView.contentMode = UIViewContentModeScaleAspectFill;
    _addImageView.clipsToBounds = YES;
    
    for (int i = 0; i < (int)(SCREEN_WIDTH - 30) / 5; i++) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(15 + 5 * i, -1, 3, 1)];
        [_webView.scrollView addSubview:view];
        view.backgroundColor = [UIColor colorFromHexRGB:@"dddddd"];
    }
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [_timer setFireDate:[NSDate distantFuture]];
}


#pragma mark - collection delegate dataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _worksArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ImageViewCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"imageViewCollectionCell" forIndexPath:indexPath];
    cell.urlImage = _worksArray[indexPath.item].worksPic;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ExhibitWorkDetailsViewController *detailsVC = [[ExhibitWorkDetailsViewController alloc]init];
    detailsVC.urlString = [NSString getURLStringWith:HOST andPaths:@[@"artgoer/api/v1/user", [NSString getUserDefaultId], @"exhibit/WorkDetailV4", [NSString stringWithFormat:@"%@", [_worksArray[indexPath.item]idField]]] andParams:@{@"token": [NSString getUserDefaultToken], @"userId": [NSString getUserDefaultId], @"workID": [NSString stringWithFormat:@"%@", [_worksArray[indexPath.item]idField]]}];
    
    [self.navigationController pushViewController:detailsVC animated:YES];
}

- (CGSize)collectionView:(UICollectionView *)collectionView topLayout:(TopCollectionLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *sizeString = _worksArray[indexPath.item].worksSize;
    CGFloat ratio = 1;
    if (sizeString != nil) {
        NSArray *array = [sizeString componentsSeparatedByString:@"x"];
        if (array.count == 2) {
            CGFloat workWidth = [array[0] floatValue];
            CGFloat workHeight = [array[1] floatValue];
            ratio = workWidth / workHeight;
        }
    }
    CGFloat width = ratio * (collectionView.frame.size.height - 30);
    return CGSizeMake(width, collectionView.frame.size.height - 30);
}

#pragma mark - webView delegate
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    self.isHaveActivity = NO;
}
#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
